import React, {useState} from 'react'
import {Button, Image, List, message} from "antd";
import {UseGetImage} from "@/hooks/useGetImage";
import {IMAGE_DIRECTION, IMAGE_TYPE, OPERATE_PRODUCT} from "@/static/enum";
import ChooseSizeDialog from "@/pages/Home/component/ChooseSizeDialog";
import {connect} from "umi";
import {useDealProduct} from "@/hooks/useDealProduct";
import './index.less'

const ProductInfo = (props: any) => {
  const {products: {size, shippingCartNum}, dispatch} = props
  const [open, setOpen] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();


  const getSelectSize = (open: boolean, newSize: any) => {
    setOpen(open)
    if (shippingCartNum === 99) {
      messageApi.open({
        type: 'warning',
        content: 'The cart is full, please clean the cart first'})
      return
    }
    if (newSize) useDealProduct(OPERATE_PRODUCT.ADD,{...props,size: newSize},dispatch )
  }

  const dealPrice = () => {
    return props.price.toFixed(2)
  }

  const showModel = () => {
   !size ? setOpen(true) : getSelectSize(false, size)
  }


  return (
    <List.Item className="ant-card-bordered ant-list-grid">
      {contextHolder}
      <div className="ant-card-head">
        <Image.PreviewGroup
          items={[
            UseGetImage(IMAGE_TYPE.PRODUCT,props.sku,IMAGE_DIRECTION.OBSERVE),
            UseGetImage(IMAGE_TYPE.PRODUCT,props.sku,IMAGE_DIRECTION.REVERSE)
          ]}
        >
          <Image
            className="ant-image"
            src={UseGetImage(IMAGE_TYPE.PRODUCT,props.sku,IMAGE_DIRECTION.OBSERVE)}
          />
        </Image.PreviewGroup>
        <div className="title text-center ant-card-head mt-4 h-12">{props.title}</div>
        <div className="mt-2 text-center">
          <span className="text-sm">{props.currencyFormat}</span>
          <span className="text-2xl">{dealPrice().split('.')[0]}</span>
          {
            dealPrice()?.toString()?.split('.')[1] ?
            (<span className="text-base">.{dealPrice()?.toString()?.split('.')[1]}</span>)
            : ''
          }
        </div>
        <div className="text-[#9C9B9B] text-base h-6 text-center">{props.description}</div>
        <Button
          type="primary"
          className="h-12 text-white text-base w-full mt-5 mb-12"
          onClick={showModel}>
          Add to cart
        </Button>
      </div>
      {
        !size
          ? <ChooseSizeDialog open={open} setSelectSize={getSelectSize}/>
          : ''
      }

    </List.Item>
  )
}

export default connect(({products}: any)=> ({products}))(ProductInfo) ;
